package xm.com.handlertest;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    public static final String TAG = "MainActivity";
    private Handler mThreadHandler;
    private Handler mMainHandler = new Handler(new Handler.Callback() {
        // 主线程接收到子线程发送的消息
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.obj != null) {
                Log.e(TAG, msg.obj.toString());
                mThreadReplyText.setText("收到子线程回复：" + msg.obj.toString());
            }
            return true;
        }
    });
    private EditText mMainEditText;
    private TextView mThreadReplyText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mMainEditText = findViewById(R.id.main_edit_text);
        mThreadReplyText = findViewById(R.id.thread_reply_text);

        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                mThreadHandler = new Handler(new Handler.Callback() {
                    // 子线程接收到主线程发送的消息并回复
                    @Override
                    public boolean handleMessage(Message msg) {
                        if (msg.obj != null) {
                            Message reply = Message.obtain();
                            reply.obj = "主线程说\"" + msg.obj.toString()+"\"";
                            // 在子线程中使用主线程中的Handler对象的引用向主线程发送消息
                            mMainHandler.sendMessage(reply);
                        }

                        return true;
                    }
                });
                Log.e("test","=======下边代码开始阻塞===begin===");
                Looper.loop();
                Log.e("test","=======代码阻塞=不能运行到这里==end===");
            }
        }).start();
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.main_send_button:
                Message message = Message.obtain();
                message.obj = mMainEditText.getText();
                // 主线程向子线程发送消息:在主线程中使用子线程中的Handler对象的引用向子线程发送消息
                if (mThreadHandler != null) {
                    mThreadHandler.sendMessage(message);
                } else {
                    while (mThreadHandler == null) {
                        Log.e(TAG, "子线程还没有完成ThreadHandler的创建");
                        if (mThreadHandler != null) {
                            Log.e(TAG, "ThreadHandler创建完成！");
                            mThreadHandler.sendMessage(message);
                        }
                    }
                }
                break;
        }
    }
}
